<?php

namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use App\Services\UserService;
use common\utils\SysCode;

class MyUserProvider extends EloquentUserProvider
{
    const USER_TYPE_USER = 'user';
    const USER_TYPE_AGENT = 'agent';
    const USER_TYPE_DEMO = 'demo';
    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];
        return password_encrypt($plain, $user->salt) === $user->getAuthPassword();
    }

    /**
     * Retrieve a user by their unique identifier.
     *
     * @param  mixed  $identifier
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier)
    {
        $keys = explode(':', $identifier);
        Auth::setDefaultDriver($keys[0]);
        $curModel = $this->getModel();
        $inputModel = '';
        switch ($keys[0]) {
            case self::USER_TYPE_USER:
                $inputModel = \App\User::class;
                break;
            case self::USER_TYPE_AGENT:
                $inputModel = \App\Agent::class;
                break;
            case self::USER_TYPE_DEMO:
                $inputModel = \App\Demo::class;
                break;
        }
        if ($curModel == $inputModel) {
            return parent::retrieveById($keys[1]);
        } else {
            return Auth::guard($keys[0])->user();
        }
    }
}
